<?php

namespace app\index\controller;

use think\Db;
use think\swoole\Server;

class Test extends Server
{
    protected $serverType = 'socket';
    protected $host = '127.0.0.1';
    protected $port = 9999;
    protected $option = [
        'worker_num' => 4,  // 开启进程数
        'daemonize' => false, // 是否守护进程模式
        'backlog' => 128,
        'heartbeat_check_interval' => 30 //每隔多少秒检测一次，单位秒，Swoole会轮询所有TCP连接，将超过心跳时间的连接关闭掉
    ];

    // 建立链接时触发
    function onOpen($server, $request)
    {
        echo "server: handshake success with fd{$request->fd}\n";
    }

    public function onReceive($server, $fd, $from_id, $data)
    {
        $server->send($fd, 'Swoole: ' . $data);
    }

    // 接受客户端消息
    public function onMessage($server, $frame)
    {
        echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
        $data = Db::table('wechat_backup_07_18_14_43_00.zl_natal_goods')->select();

        $dataStr = json_encode($data,JSON_UNESCAPED_UNICODE);

        // 向客户端发送消息
        $server->push($frame->fd, $dataStr);
    }

    // 链接关闭时触发
    public function onClose($ser, $fd)
    {
        echo "client {$fd} closed\n";
    }
}
